package com.conversationboard.standalone.checkdb;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.LinkedList;
import java.util.List;

import com.conversationboard.database.Database;

public class FixUnansweredThreads {

	public static class Thread {

		private int boardId;
		private int threadId;


		public int getBoardId() {
			return boardId;
		}


		public void setBoardId(int boardId) {
			this.boardId = boardId;
		}


		public int getThreadId() {
			return threadId;
		}


		public void setThreadId(int threadId) {
			this.threadId = threadId;
		}


		public Thread(int boardId, int threadId) {
			this.boardId = boardId;
			this.threadId = threadId;
		}

	}


	public static void fixUnansweredThreads() throws Throwable {

		List<Thread> threads = new LinkedList<Thread>();
		List<Thread> threadsToFix = new LinkedList<Thread>();

		Connection connection = Database.getConnection();

		PreparedStatement statement = connection.prepareStatement("SELECT boardid, threadid FROM threads WHERE unanswered=true");
		statement.execute();

		ResultSet resultSet = statement.getResultSet();

		while (resultSet.next()) {
			int boardId = resultSet.getInt("boardid");
			int threadId = resultSet.getInt("threadid");
			Thread thread = new Thread(boardId, threadId);
			threads.add(thread);
		}

		statement.close();

		PreparedStatement find = connection.prepareStatement("SELECT COUNT(*) as count FROM messages WHERE boardid=? and threadid=?");

		for (Thread t : threads) {

			find.setInt(1, t.getBoardId());
			find.setInt(2, t.getThreadId());

			find.execute();

			ResultSet r = find.getResultSet();
			int count = 1;

			while (r.next()) {
				count = r.getInt("count");
			}

			if (count > 1) {
				threadsToFix.add(t);
				System.out.println(t.getBoardId() + ":" + t.getThreadId() + " has been answered");
			}
		}

		PreparedStatement update = connection.prepareStatement("UPDATE threads SET unanswered=false WHERE boardid=? AND threadid=?");

		for (Thread t : threadsToFix) {
			update.setInt(1, t.getBoardId());
			update.setInt(2, t.getThreadId());
			update.addBatch();
		}

		update.executeBatch();

		connection.close();
	}

}
